package com.toune.movie.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.utils.AVFileUtil;
import com.toune.movie.R;
import com.toune.movie.base.AppConstant;
import com.toune.movie.base.myUtil.GetTimeUtils;
import com.toune.movie.base.myUtil.MyUtil;
import com.toune.movie.base.myUtil.ThreadPoolManager;
import com.toune.movie.mvp.activity.MainActivity;
import com.vondear.rxtool.RxFileTool;
import com.vondear.rxtool.RxZipTool;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

public class MonitorService extends Service {
    public static final String ACTION_BACK_HOME = "com.byd.recorder.ACTION_BACK_HOME";
    public static final String ACTION_SHOW_RECORDER = "com.byd.recorder.ACTION_SHOW_RECORDER";

    private static final int NOTIFICATION_DI = 1234;
    private static Intent intent;

    private WindowManager windowManager;
    private SurfaceView surfaceView;
    private Camera camera = null;
    private MediaRecorder mediaRecorder = null;
    /* RecorderManager manages the job of video recording */
    private LocalBroadcastManager mLocalBroadcastManager;
    private String fileName;
    private Timer mTimer;
    private boolean isRecording;
    private int mTimeCount = 0;
    private int MAX_TIME = 150;
    private TimerTask timerTask;
    private File file;

    @Override
    public void onCreate() {
        super.onCreate();
        addView();
    }

    private void addView() {
        // Start foreground service to avoid unexpected kill
        Notification notification = new Notification.Builder(this)
                .setContentTitle("Background Video Recorder")
                .setContentText("")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .build();
        startForeground(1234, notification);

        // Create new SurfaceView, set its size to 1x1, move it to the top left corner and set this service as a callback
        windowManager = (WindowManager) MonitorService.this.getSystemService(Context.WINDOW_SERVICE);
        surfaceView = new SurfaceView(this);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                1, 1,
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT
        );

//全屏显示在最上图层上
//        final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
//                WindowManager.LayoutParams.WRAP_CONTENT,
//                WindowManager.LayoutParams.WRAP_CONTENT,
//                WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
//                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
//                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
//                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
//                PixelFormat.TRANSLUCENT
//        );


        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        windowManager.addView(surfaceView, layoutParams);
        surfaceView.getHolder().addCallback(callback);
    }

    @Override
    public void onDestroy() {

        mediaRecorder.stop();
        mediaRecorder.reset();
        mediaRecorder.release();
        camera.lock();
        camera.release();
        windowManager.removeView(surfaceView);
        if (file.exists()) {
            ThreadPoolManager.getInstatnce().createThreadPool().execute(uploadRun);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            mediaRecorder = new MediaRecorder();
            camera = Camera.open(1);
            if (camera != null) {
                camera.unlock();
                mediaRecorder.setCamera(camera);
            }
            // 这两项需要放在setOutputFormat之后
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            // Set output file format
            mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

            mediaRecorder.setVideoSize(640, 480);
            mediaRecorder.setVideoFrameRate(30);
            mediaRecorder.setVideoEncodingBitRate(1024 * 1024);
            mediaRecorder.setOrientationHint(90);
            mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());

            getOutputMediaFile();
            mediaRecorder.setOutputFile(
                    fileName
            );
            try {
                mediaRecorder.prepare();
                mediaRecorder.start();
                isRecording = true;
            } catch (Exception e) {
                Log.e("mediaRecorder", e.toString());
                camera.release();
            }
            if (mTimer == null) {
                mTimer = new Timer();
            }
            if (timerTask == null) {
                timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        if (isRecording) {
                            mTimeCount++;
                            if (mTimeCount == MAX_TIME) {
                                mainHandler.post(sendVideo);
                            }
                        }
                    }
                };
                mTimer.schedule(timerTask, 0, 500);
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }
    };

    @SuppressLint("HandlerLeak")
    private Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };
    private Runnable sendVideo = new Runnable() {
        @Override
        public void run() {
            recordStop();
        }
    };

    /**
     * 停止录制
     */
    private void recordStop() {
        if (isRecording) {
            isRecording = false;
            mediaRecorder.stop();
            releaseMediaRecorder();
            camera.lock();
//            if (mTimer != null) mTimer.cancel();
            mTimeCount = 0;
            ThreadPoolManager.getInstatnce().createThreadPool().execute(uploadRun);
            windowManager.removeView(surfaceView);
            addView();
        }
    }

    private void releaseMediaRecorder() {
        if (mediaRecorder != null) {
            mediaRecorder.reset();   // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = null;
        }
    }

    Runnable uploadRun = new Runnable() {
        @Override
        public void run() {
            String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
            try {
                AVFile file = AVFile.withAbsoluteLocalPath(name, fileName);
                AVObject avObject = new AVObject(AppConstant.TAB_VIDEO);
                avObject.put("video", file);
                avObject.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(AVException e) {
                        if (e == null) {
                            RxFileTool.deleteFile(fileName);
                        } else {
                            RxFileTool.deleteFile(fileName);
                        }
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * Create a File for saving an image or video
     */
    private File getOutputMediaFile() {
        fileName = MyUtil.getAppVideoPath() + "/" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
        file = new File(fileName);
        return file;
    }

    public static void startThis(Context context) {
        if (intent == null && (AppConstant.ISVIDEO == 1)) {
            intent = new Intent(context, MonitorService.class);
            context.startService(intent);
        }
    }
}